package com.kehao.account_book.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kehao.account_book.pojo.ClientExpenditure;
import com.kehao.account_book.pojo.Expenditure;
import com.kehao.account_book.pojo.User;
import com.kehao.account_book.service.ExpenditureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kehao
 * @date 2020/2/22-15:51
 */
@RestController
public class ExpenditureController {
    @Autowired
    private ExpenditureService service;

    @RequestMapping("sync")
    public String sync(@RequestBody String json){//只将服务器有的但客户端没有的返回
        Map map = new Gson().fromJson(json,new TypeToken<Map<String,Object>>(){}.getType());
        String username  = (String) map.get("username");
        int year = (int)((double)map.get("year"));
        int month = (int)((double)map.get("month"));
        String listStr = (String)map.get("list");
        List<ClientExpenditure> list = new Gson().fromJson(listStr,new TypeToken<List<ClientExpenditure>>(){}.getType());
        int maxAnchor = (int)((double)map.get("anchor")); //客户端最大的anchor
        int modify = service.getMaxModify(username)+1;//获取服务器当前用户最大的modify,本次更新数据modify会在此基础上+1
        for(int i = 0;i<list.size();i++){
            ClientExpenditure e = list.get(i);
            if(e.getStatus() == ClientExpenditure.STATUS_ADD){
                service.addExpenditure(e,modify);
            }else if(e.getStatus() == ClientExpenditure.STATUS_LOCAL_CHANGE){
                service.updateExpenditure(e,modify);
            }else if(e.getStatus()==ClientExpenditure.STATUS_REMOVE){
                service.removeExpenditure(e);
            }
        }
        //只更新那个月的
        List<ClientExpenditure> listReturn = service.getUpdateClientExpenditureList(maxAnchor,username,year,month);
        String listReturnStr = new Gson().toJson(listReturn);
        Map mapReturn = new HashMap<>();
        mapReturn.put("modify",modify);
        mapReturn.put("list",listReturnStr);
        String jsonReturn = new Gson().toJson(mapReturn);
        return jsonReturn;
    }

}
